package com.yunshang.shoppingmall.shopping.User;
import com.yunshang.shoppingmall.common.MD5Util;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.common.loginOut;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.entity.Finace.Finace;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.Finace.FinaceJiFenService;
import com.yunshang.shoppingmall.service.Finace.FinaceService;
import com.yunshang.shoppingmall.service.Finace.FinaceTotalService;
import com.yunshang.shoppingmall.service.User.UserNoService;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/wap")
public class UserCenterController {
    @Autowired
    SysUserNoService  sysUserNoService;
    @Autowired
    ConfigService configService;
    @Autowired
    FinaceService finaceService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    UserService userService;
    @Autowired
    AddressService addressService;
    @Autowired
    OrderService orderService;
    @Autowired
    FinaceJiFenService finaceJiFenService;
    @Autowired
    FinaceTotalService finaceTotalService;
    @Autowired
    WithdrawalsService withdrawalsService;
    @Autowired
    FianceConfig fianceConfig;
    @Autowired
    UserNoOrderService userNoOrderService;
    @Autowired
    ProductService productService;
    @Autowired
    CollectService collectService;
    @Autowired
    OrderAddressService orderAddressService;
    @Autowired
    OrderListService orderListService;
    @Autowired
    UserNoService userNoService;

    @RequestMapping("/openUserCenter")
    public ModelAndView openUserCenter(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<UserNo> userNoList = null;
        String userNo1 = null;
        UserNo userNo2 = null;
        int rank = 0;//用户等级ID
        int userId = 0;
        String phone = null;
        UserRank userRank = null;
        String type = "0";//登录类型:密码登录为0.手机登录为1
        List<UserNo> userNoList1 = new ArrayList<>();
        Logger logger = LoggerFactory.getLogger(UserCenterController.class);
        logger.info("打开用户中心");
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        User userList = (User) request.getSession().getAttribute("userList");
        //System.out.println("打开用户中心"+userList.toString());
        int checkphone = 0;
        try {
            checkphone = (int) request.getSession().getAttribute("phone");
        } catch (Exception e) {
        }

        int activityUserNoSum=0;

        if (userNo != null && checkphone == 1) {//用户密码登录成功
            String no = userNo.getUserNo();
            ModelAndView modelAndView = new ModelAndView("shoppingApi/user/memberCenter");
            UserNo no1 = sysUserNoService.selectUserNoByUserNo(no);
            type = "0";//密码登录
            if (no1 != null) {
                rank = no1.getRank();//用户等级
                if (rank <= 0) {
                    rank = 19;//默认为游客
                }
                userRank = userRankService.selectByPrimaryKey(rank);
                userId = no1.getUserId();//用户id
                System.out.println("userId=" + userId);
                User user = userService.selectByPrimaryKey(userId);
                if (user != null) {
                    System.out.println("密码登录：" + user.getPhone());
                    phone = user.getPhone();
                    User user1 = userService.selectUserByPhone(phone);
                    if (user1 != null) {
                        int userId1 = user1.getUserId();
                        userNoList1 = userNoService.selectUserNoByUserId(userId1);
                    }

                }
                map.put("userRank", userRank);

                System.out.println("读取销售量");
                //读取销售量
                activityUserNoSum = sysUserNoService.WActivityUserNoSum(no1.getId());

            }

            System.out.println("销量："+activityUserNoSum);

            map.put("userNoList", userNoList1);
            map.put("userNo", no1);
            map.put("type", type);
            map.put("activityUserNoSum", activityUserNoSum);
            modelAndView.addObject("map", map);
            return modelAndView;
        } else if (userList != null && checkphone == 2) {//用户手机号登录成功！
            System.out.println("用户手机号登录成功");
            ModelAndView modelAndView = new ModelAndView("shoppingApi/user/memberCenter");
            type = "1";
            //手机号登录成功，就显示登录的数据
            userId = userList.getUserId();//用户id
            List<UserNo> userNos = sysUserNoService.selectUserNoByUserId(userId);//用户编号
            if (checkphone == 2) {
                userNo2 = userNo;
            } else {
                userNo2 = userNos.get(0);
            }
            userNoList1 = userNos;
            request.getSession().setAttribute("userNo", userNo2);
            if (userNo2 != null) {
                rank = userNo2.getRank();//用户等级ID
                userRank = userRankService.selectByPrimaryKey(rank);//用户等级
                System.out.println("读取销售量B");
                activityUserNoSum = sysUserNoService.WActivityUserNoSum(userNo2.getId());
            }
            map.put("userRank", userRank);
            map.put("type", type);
            map.put("userNo", userNo2);//用户编号对象
            map.put("userNoList", userNoList1);
            System.out.println("销量B："+activityUserNoSum);
            map.put("activityUserNoSum", activityUserNoSum);
            modelAndView.addObject("map", map);
            return modelAndView;
        } else {
            ModelAndView modelAndView = new ModelAndView("shoppingApi/user/loginbypassword");
            return modelAndView;

        }

    }


    //我的钱包
    @ResponseBody
    @RequestMapping("/mywallet")
    public ModelAndView mywallet(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String userNo1 = request.getParameter("userNo");
        double balance1 = 0.00;
        double balance2 = 0.00;
        double balance3 = 0.00;
        double balance4 = 0.00;
        String fType = "1";
        FinaceTotal finaceTotal1 = null;
        FinaceTotal finaceTotal2 = null;
        FinaceTotal finaceTotal3 = null;
        FinaceTotal finaceTotal4 = null;
        int userId = 0;
        if (userNo1 != null) {
            map.put("userNo", userNo1);
            //编号查询用户ID
            UserNo userNo = sysUserNoService.selectUserNoByUserNo(userNo1);
            if (userNo != null) {
                userId = userNo.getId();
            }


            //根据用户ID查询用户财务信息
            finaceTotal1 = finaceTotalService.selectFinaceTotal(userId, fType);//查询积分

            //查询消费积分
            fType = "4";
            finaceTotal4 = finaceTotalService.selectFinaceTotal(userId, fType);

            //查询折扣券
            fType = "3";
            finaceTotal3 = finaceTotalService.selectFinaceTotal(userId, fType);

            //查询购物券
            fType = "2";

            finaceTotal2 = finaceTotalService.selectFinaceTotal(userId, fType);
            if (finaceTotal1 != null) {
                balance1 = finaceTotal1.getBalance();
            }
            if (finaceTotal2 != null) {
                balance2 = finaceTotal2.getBalance();
            }
            if (finaceTotal3 != null) {
                balance3 = finaceTotal3.getBalance();
            }
            if (finaceTotal4 != null) {
                balance4 = finaceTotal4.getBalance();
            }
        }

        Config userConfig = configService.selectByPrimaryKey(1);//货币名称显示
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/mywallet");
        map.put("balance1", balance1);
        map.put("balance2", balance2);
        map.put("balance3", balance3);
        map.put("balance4", balance4);
        map.put("user", userNo1);
        map.put("config", userConfig);
        map.put("WebConfig", userConfig.getFinacename1());
        map.put("userNo", userNo1);
        modelAndView.addObject("map", map);
        return modelAndView;
    }

    // 提现
    @ResponseBody
    @RequestMapping("/transfer")
    public ModelAndView transfer() {
        String htmlName = "shoppingApi/user/transfer";
        ModelAndView modelAndView = new ModelAndView(htmlName);
        return modelAndView;
    }

    // 转让
    @ResponseBody
    @RequestMapping("/withdraw")
    public ModelAndView withdraw() {
        String htmlName = "shoppingApi/user/withdraw";
        ModelAndView modelAndView = new ModelAndView(htmlName);
        return modelAndView;
    }

    // 404错误页面
    @ResponseBody
    @RequestMapping("/error404")
    public ModelAndView error404() {
        String htmlName = "shoppingApi/user/error404";
        ModelAndView modelAndView = new ModelAndView(htmlName);
        return modelAndView;
    }

    // 发布评论
    @ResponseBody
    @RequestMapping("/comment")
    public ModelAndView comment(HttpServletRequest request, String orderNo) {
        String htmlName = "shoppingApi/user/comment";
        ModelAndView modelAndView = new ModelAndView(htmlName);


        Map<String, Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel = 0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel = userNo1.getRank();
        }

        OrderList orderList = orderListService.selectOrder(orderNo);
        map.put("list", orderList);
        modelAndView.addObject("orderList", map);
        return modelAndView;
    }

    //保存评论到订单
    @ResponseBody
    @RequestMapping("/addOrderComment")
    public Response addOrderComment(String orderNo, String content) {
        Order order = orderService.selectByNo(orderNo);
        Date d = new Date();
        if (order != null) {
            order.setComment(content);
            order.setCommentTime(d);
        }
        int res = orderService.updateByPrimaryKeySelective(order);
        return new Response(MessageConstants.MSG_SYS_ERROR, res, "");
    }

    // 我的评论
    @ResponseBody
    @RequestMapping("/mycomment")
    public ModelAndView mycomment(HttpServletRequest request) {
        String htmlName = "shoppingApi/user/mycomment";
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;//用户编号id
        int memberLevel = 0;//等级
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel = userNo1.getRank();
        }
        List<OrderList> orderList = orderListService.selectOrderListComment(memberUserId);
        orderList = setOrderList(orderList);
        orderList = paging(orderList, 1, 5);
        map.put("list", orderList);
        modelAndView.addObject("orderList", map);
        return modelAndView;
    }

    // 个人资料
    @ResponseBody
    @RequestMapping("/profile")
    public ModelAndView profile(HttpServletRequest request) {
        String htmlName = "shoppingApi/user/profile";
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel = 0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel = userNo1.getRank();
        }

        UserNo userNo = userNoService.selectUserInfo(memberUserId);
        map.put("userInfo", userNo);
        modelAndView.addObject("userInfo", map);
        return modelAndView;
    }

    //个人资料保存
    @ResponseBody
    @RequestMapping("/addProfile")
    public Response addProfile(HttpServletRequest request, String nickName) {
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel = 0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel = userNo1.getRank();
        }
        UserNo userNo = userNoService.selectByPrimaryKey(memberUserId);
        System.out.println(userNo.toString() + "---");
        if (userNo != null) {
            userNo.setName(nickName);
        }
        int res = userNoService.updateByPrimaryKeySelective(userNo);
        return new Response(MessageConstants.MSG_SYS_ERROR, res, "");
    }

    public List<OrderList> setOrderList(List<OrderList> orderLists) {
        for (int i = 0; i < orderLists.size(); i++) {
            int count = 0;
            for (int j = 0; j < orderLists.get(i).getOrderDetailsProducts().size(); j++) {
                count += orderLists.get(i).getOrderDetailsProducts().get(j).getProductCount();
            }
            orderLists.get(i).setCount(count);
        }
        return orderLists;
    }

    public List<OrderList> paging(List<OrderList> list, Integer page, Integer pageSize) {
        int size = list.size();
        int pageCount = size / pageSize;
        int fromIndex = pageSize * (page - 1);
        int toIndex = fromIndex + pageSize;
        if (toIndex >= size) {
            toIndex = size;
        }
        if (page > pageCount + 1) {
            fromIndex = 0;
            toIndex = 0;
        }
        return list.subList(fromIndex, toIndex);
    }

    //查看积分明细
    @RequestMapping("/financeDetail")
    public ModelAndView financeDetail(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        int userId = 0;
        int fTypes = 0;
        List<Finace> finaceList = null;
        String htmlName = "";
        String fType = request.getParameter("fType");

        switch (fType) {
            case "1":
                htmlName = "shoppingApi/user/balancedetail1";
                break;
            case "2":
                htmlName = "shoppingApi/user/balancedetail2";
                break;
            case "3":
                htmlName = "shoppingApi/user/balancedetail3";
                break;
            case "4":
                htmlName = "shoppingApi/user/balancedetail4";
                break;
        }

        ModelAndView modelAndView = new ModelAndView(htmlName);
        //用户编号查询积分明细
        String userNo = request.getParameter("userNo");
        if (userNo != null) {
            UserNo userNo1 = sysUserNoService.selectUserNoByUserNo(userNo);
            if (userNo1 != null) {
                userId = userNo1.getId();
                FinaceToData finaceToData = new FinaceToData();
                if (fType != null) {
                    fTypes = Integer.parseInt(fType);
                }
                finaceToData.setClassify(fTypes);
                finaceToData.setUserId(userId);
                finaceList = finaceService.selectFinaceDetailsByUserId(finaceToData);
                Config config=configService.selectByPrimaryKey(1);
                map.put("finaceList", finaceList);
                map.put("config",config);
            }
        }
        modelAndView.addObject("map", map);
        return modelAndView;
    }

    // 切换账号-编号登录
    @ResponseBody
    @RequestMapping("/ChangeUserNo")
    public ModelAndView ChangeUserNo(HttpServletRequest request, String userId, String userNo, String type) {
        HttpSession session = request.getSession();
        Map<String, Object> map = new HashMap<>();
        User user = null;
        int userId1 = 0;
        UserNo userNo1 = null;
        String htmlName = "shoppingApi/user/verifyphonenumber";
        ModelAndView modelAndView = new ModelAndView(htmlName);
        userNo1 = (UserNo) session.getAttribute("userNo");
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        if (userId != null && userId != "") {
            int userIds = Integer.parseInt(userId);
            user = userService.selectByPrimaryKey(userIds);
        }
        if (userNo != "" && userNo != null && userNo1 == null) {
            userNo1 = sysUserNoService.selectUserNoByUserNo(userNo);
        }
        map.put("user1", user);
        map.put("user", userNo1);
//        System.out.println("userNo1===="+userNo1.getName()+"no=="+userNo1.getUserNo());
//        map.put("phone",userNo1.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
        map.put("userNo", userNo);
        if (userNo != null && userNo != "") {
            UserNo userNo2 = sysUserNoService.selectUserNoByUserNo(userNo);
            request.getSession().setAttribute("userNoCheckCode", userNo2);
            //request.getSession().setAttribute("userNo",userNo2);
        }
        modelAndView.addObject("map", map);
        return modelAndView;

    }

    // 切换账号-编号登录
    @ResponseBody
    @RequestMapping("/ChangeUserNo1")
    public String ChangeUserNo1(HttpServletRequest request, String userNo) {
        HttpSession session = request.getSession();
        UserNo userNoNew = sysUserNoService.selectUserNoByUserNo(userNo);
        if (userNoNew != null) {
            System.out.println("s1");
            session.setAttribute("userNo", userNoNew);
            return "1";
        } else {
            System.out.println("s2");
            session.setAttribute("userNo", null);
            return "0";
        }
    }

    //会员中心账户设置
    @ResponseBody
    @RequestMapping("/accountsetting")
    public ModelAndView accountsetting(HttpServletRequest request) {

        String htmlName = "shoppingApi/user/accountsetting";
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();
        String userNo = request.getParameter("userNo");
        if (userNo != "" && userNo != null) {
            modelAndView.addObject("userNo", userNo);
        }
        modelAndView.addObject("userNoSession", userNo1);
        return modelAndView;
    }

    //退出登陆
    @ResponseBody
    @RequestMapping("/userLoginOut")
    public Response JsonUserNoOut(HttpServletRequest request) {
//        if (loginOut.checkLogin(request)) {
//            HttpSession session = request.getSession();
//            session.removeAttribute("userNo");
//        }
        HttpSession session = request.getSession();
        session.removeAttribute("userNo");
        session.removeAttribute("userList");
        return new Response(MessageConstants.MSG_SUCCESS, null, "");
    }

    //会员中心我的地址
    @ResponseBody
    @RequestMapping("/myAddress")
    public ModelAndView myAddress(HttpServletRequest request) {
        String htmlName = "shoppingApi/user/myaddresses";
        String isMoreAddress=request.getParameter("isMoreAddress");
        request.getSession().setAttribute("isMoreAddress", isMoreAddress);
        System.out.println("isMoreAddress:"+isMoreAddress);
        String updateAddressURL = request.getParameter("updateAddressURL");
        request.getSession().setAttribute("updateAddressURL", updateAddressURL);
        String orderNo = request.getParameter("orderNo");//订单详情页面参数 用于30分钟内的订单可修改参数
        request.getSession().setAttribute("orderNo", orderNo);
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");//登录
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();

        List<Address> list = addressService.selectByUserId(userNo1.getId());//

        map.put("address", list);
        modelAndView.addObject("list", map);
        return modelAndView;
    }


    //会员中心增加地址
    @ResponseBody
    @RequestMapping("/myAddressAdd")
    public ModelAndView myAddressAdd(HttpServletRequest request) {
        String htmlName = "shoppingApi/user/addaddress";
        String updateAddressURL = request.getParameter("updateAddressURL");
        request.getSession().setAttribute("updateAddressURL", updateAddressURL);
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();
        List<Address> list = addressService.selectByUserId(userNo1.getId());
        map.put("address", list);
        modelAndView.addObject("list", map);
        return modelAndView;
    }

    //会员中心修改新增地址
    @ResponseBody
    @RequestMapping("/addressAddOrEdit")
    public Response addressAddOrEdit(HttpServletRequest request, String id, String addressIds, String detailAddress, String name, String phone, String isdefault) {
        String logname=name==null?"":name;
        String logphone=phone==null?"":phone;
        if("".equals(logname)||"".equals(logphone)){
            return new Response(MessageConstants.MSG_SYS_ERROR, -1, "失败002!");
        }
        HttpSession session = request.getSession();
        String updateAddressURL = (String) request.getSession().getAttribute("updateAddressURL");
        String isMoreAddress = (String) request.getSession().getAttribute("isMoreAddress");
        int isMoreAddressInt=0;
        try {
            isMoreAddressInt=Integer.parseInt(isMoreAddress);
        }catch (Exception e){}
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        String orderNo = (String) session.getAttribute("orderNo");
        int memberUserId = 0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
        }
        int addressIdSXX=0,provinceIdS=0,cityIdS=0,areaIdS=0,isDefaultS=0;
        try {
            addressIdSXX = Integer.parseInt(id);
            isDefaultS = Integer.parseInt(isdefault);//默认值为1，否则为0
        }catch (Exception E){}
        try {
            if (!addressIds.equals("0")) {
                String[] names = addressIds.split(",");
                provinceIdS = Integer.parseInt(names[0]);
                cityIdS = Integer.parseInt(names[1]);
                areaIdS = Integer.parseInt(names[2]);
            }
        }catch (Exception er){}

        Address address=new Address();
        Integer res = 0;
        try {
            if (addressIdSXX > 0) {//编辑地址
                if(provinceIdS>0&&cityIdS>0&&areaIdS>0){
                    address = addressService.selectByPrimaryKey(addressIdSXX);
                    address =setAddress(provinceIdS,cityIdS,areaIdS,detailAddress,phone,name,isMoreAddressInt,address);
                    System.out.println("isDefaultS:"+isDefaultS);
                    if (isDefaultS == 1) {
                        addressService.updateAddressStateByUserId(memberUserId);
                    }
                    address.setIsdefault(isDefaultS);
                    res = addressService.updateByPrimaryKey(address);
                }
            } else {//增加地址
                if(provinceIdS>0&&cityIdS>0&&areaIdS>0){
                    address=setAddress(provinceIdS,cityIdS,areaIdS,detailAddress,phone,name,isMoreAddressInt,null);
                    if (isDefaultS == 1) {
                        addressService.updateAddressStateByUserId(memberUserId);
                    }
                    address.setIsdefault(isDefaultS);
                    address.setUserId(memberUserId);
                    res = addressService.insert(address);
                }
            }
        }catch (Exception e){
            return new Response(MessageConstants.MSG_SYS_ERROR, 0, "失败001!");
        }

        if (orderNo != null&&!"".equals(orderNo)&&!"null".equals(orderNo)) {
                int reso=0;
                OrderAddress orderAddress = new OrderAddress();
                orderAddress.setLogType(2);
                orderAddress.setProvinceId(provinceIdS);
                orderAddress.setCityId(cityIdS);
                orderAddress.setAreaId(areaIdS);
                orderAddress.setUserId(memberUserId);
                orderAddress.setName(name);
                orderAddress.setPhone(phone);
                orderAddress.setDetailAddr(detailAddress);
                OrderAddress orderAddress1=orderAddressService.selectByOrderAddress(orderAddress);
                if(orderAddress1!=null){
                    orderService.updateOrderAddressId(orderAddress1.getId().toString(), orderNo);
                }else {
                    reso = orderAddressService.insertSelective(orderAddress);
                }
                if (reso > 0) {
                    int res1 = orderService.updateOrderAddressId(orderAddress.getId().toString(), orderNo);
                }
        }
        if (res > 0) {
            return new Response(MessageConstants.MSG_SYS_ERROR, 1, updateAddressURL);
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR, 0, "失败!");
        }
    }

    private Address setAddress(int a1,int a2,int a3,String b1,String b2,String b3,int b4,Address address1){
        if(address1!=null){
            address1.setProvinceId(a1);
            address1.setCityId(a2);
            address1.setAreaId(a3);
            address1.setDetailAddr(b1);
            address1.setName(b3);
            address1.setPhone(b2);
            address1.setIsMoreAddress(b4);
            return address1;
        }else {
            Address address=new Address();
            address.setProvinceId(a1);
            address.setCityId(a2);
            address.setAreaId(a3);
            address.setDetailAddr(b1);
            address.setPhone(b2);
            address.setName(b3);
            address.setIsMoreAddress(b4);
            return address;
        }
    }


    //会员中心删除地址
    @ResponseBody
    @RequestMapping(value = "/addressDelete", method = RequestMethod.POST)
    public Response addressDelete(String addressId) {
        Integer res = addressService.deleteByPrimaryKey(Integer.parseInt(addressId));
        return new Response(MessageConstants.MSG_SYS_ERROR, res, "");
    }

    //查询用户编号的积分
    @ResponseBody
    @RequestMapping("/selectUserNoFinaceByUserId")
    public Map<String, Object> selectUserNoFinaceByUserId(HttpServletRequest request) {
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        Map<String, Object> map = new HashMap<>();
        int userId = 0;
        FInaceJiFen finace = null;//积分
        BigDecimal balance = null;//余额
        double balances = 0.00;
        if (userNo != null) {
            userId = userNo.getUserId();
            finace = finaceJiFenService.selectByPrimaryKey(userId);
            if (finace != null) {
                balance = finace.getBalance();
                if (balance != null) {
                    balances = balance.doubleValue();
                }
            }
        }
        map.put("balance", balances);
        return map;
    }

    //积分进行支付
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/payByJiFen", method = RequestMethod.POST)
    public Map<String, Object> payByJiFen(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        int cashs = 0;
        int userId = 0;
        int row = 0;
        double sum = 0.00;
        double balances = 0.00;
        BigDecimal balance1 = null;
        FInaceJiFen fInaceJiFen = null;//积分
        BigDecimal balance = null;//余额
        String payState = "0";//支付状态“0”支付失败，“1”支付成功！
        if (userNo != null) {
            FInaceJiFen fInaceJiFen1 = new FInaceJiFen();
            String cash = request.getParameter("cash");
            if (cash != null && cash != "") {
                cashs = Integer.parseInt(cash);//需要支付的金额
                //更新积分余额
                userId = userNo.getUserId();//用户编号Id
                fInaceJiFen1.setUserId(userId);
                fInaceJiFen = finaceJiFenService.selectByPrimaryKey(userId);//积分
                if (fInaceJiFen != null) {
                    balance = fInaceJiFen.getBalance();
                    if (balance != null) {
                        balances = balance.doubleValue();
                        sum = balances - cashs;
                        balance1 = BigDecimal.valueOf(sum);
                        fInaceJiFen1.setBalance(balance1);
                    }
                }
                row = finaceJiFenService.updateBalanceByUserId(fInaceJiFen1);//更新积分
                if (row > 0) {
                    //保存积分每一次交易记录
                    Finace finace = new Finace();
                    finace.setAmount(new BigDecimal(cashs));//金额;
                    finace.setBalance(balance1);//余额
                    finace.setUserId(userId);//用户ID
                    finace.setFinaceTime(new Timestamp(System.currentTimeMillis()));//时间
                    finace.setOpratorId(1);//操作Id
                    finace.setRemark("支出");//标记
                    finace.setFinaceType("777");//类型
                    int rows = finaceService.insert(finace);
                    payState = "1";
                } else {
                    payState = "0";
                }
            } else {//金额不对
                payState = "0";
            }
        }
        map.put("payState", payState);
        return map;
    }


    //会员中心收益
    @ResponseBody
    @RequestMapping("/earnings")
    public ModelAndView earnings(HttpServletRequest request, String type, String days) {
        Map<String, Object> map = new HashMap<>();
        String htmlName = "shoppingApi/user/dayearnings";
        int day = 0;
        Timestamp startTime = null;
        Timestamp endTime = null;
        if ("1".equals(type)) {
            htmlName = "shoppingApi/user/dayearnings";
        }
        if ("2".equals(type)) {
            htmlName = "shoppingApi/user/weekearnings";
        }
        if ("3".equals(type)) {
            htmlName = "shoppingApi/user/monthearnings";
        }

        if (days != null && days != "") {
            day = Integer.parseInt(days);
        }

        if (day == 1) {//每天
            startTime = new Timestamp(DateUtils.getDayBegin().getTime());
            endTime = new Timestamp(DateUtils.getDayEnd().getTime());
        } else if (day == 7) {//每周
            Date date = new Date();
            String date1 = DateUtils.getTimeInterval(date);
            String dateTime[] = date1.split(",");
            startTime = Timestamp.valueOf(dateTime[0]);
            endTime = Timestamp.valueOf(dateTime[1]);

        } else if (day == 30) {//每月
            Date startMonth = DateUtils.getBeginDayOfMonth();
            Date endMonth = DateUtils.getEndDayOfMonth();
            startTime = new Timestamp(startMonth.getTime());
            endTime = new Timestamp(endMonth.getTime());
        }
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int userNoId = 0;
        List<Finace> finaceList = null;
        Config config = null;
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        if (userNo1 != null) {
            userNoId = userNo1.getId();
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);

        //收益明细
        OrderToData orderToData = new OrderToData();
        orderToData.setClassify(1);
        orderToData.setFinaceType("888");
        orderToData.setEndTime(endTime);
        orderToData.setStartTime(startTime);
        orderToData.setUserNoId(userNoId);

        List<Finace> finaceList1 = finaceService.selectFinaceByUserIdAndFinaceType(orderToData);
        map.put("finaceList", finaceList1);

        modelAndView.addObject("map", map);
        return modelAndView;
    }


    //    //会员中心取消订单
    @ResponseBody
    @RequestMapping("/cancelOrder")
    public Response cancelOrder(String No) {
        Order order = orderService.selectByNo(No);
        if (!order.getOrderStatus().equals("701")) {
            return new Response(MessageConstants.MSG_SYS_ERROR, 0, "订单状态有误!");
        } else {
            order.setOrderStatus("706");
            Integer res = orderService.updateByPrimaryKey(order);
            if (res <= 0) {
                return new Response(MessageConstants.MSG_SYS_ERROR, res, "订单取消失败!");
            } else {
                return new Response(MessageConstants.MSG_SYS_ERROR, res, "成功!");
            }
        }
    }


    //会员中心我的分享
    @ResponseBody
    @RequestMapping("/myrecommend")
    public ModelAndView myrecommend(HttpServletRequest request) {

        String htmlName = "shoppingApi/user/myrecommend";
        int userNoId = 0;
        Timestamp timestamp = null;
        List<Order> orderList = new ArrayList<>();
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");

        if (!loginOut.checkLogin(request)) {
            userNo1 = null;

        }
        //查询用户的推荐人
        int agent=0;
        if (userNo1 != null) {
            userNoId = userNo1.getId();
            agent=userNo1.getAgent();
        }
        //查询我的所有推荐人
        List<UserNoOrder> userNoOrderList = userNoOrderService.selectUserNoOrderByReCommend(userNoId);

        ModelAndView modelAndView = new ModelAndView(htmlName);
        modelAndView.addObject("userNoOrderList", userNoOrderList);
        modelAndView.addObject("agent", agent);
        return modelAndView;
    }

    //会员中心我的分享
    @ResponseBody
    @RequestMapping("/myactivity")
    public ModelAndView myactivity(HttpServletRequest request) {

        String htmlName = "shoppingApi/user/myactivity";
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");

        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        //查询用户的销售详情
        ModelAndView modelAndView = new ModelAndView(htmlName);

        int userNoId=0;
        if (userNo1 != null) {
            userNoId = userNo1.getId();
        }
        if(userNoId>0) {
            //查询用户的销售详情
            List<Activity> activityList = sysUserNoService.WActivityUserNoDetails(userNoId);
            modelAndView.addObject("activityList", activityList);
        }
        else {
            modelAndView.addObject("activityList", null);
        }
        return modelAndView;
    }


    //会员中心商品收藏
    @ResponseBody
    @RequestMapping("/productcollect")
    public ModelAndView productcollect(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String htmlName = "shoppingApi/user/productcollect";
        List<Collect> collectList = null;
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);
        if (userNo1 != null) {
            collectList = collectService.selectAllByUserNoId(userNo1.getId());
            map.put("collectList", collectList);
        }
        modelAndView.addObject("map", map);
        return modelAndView;
    }


    //会员中心我的地址编辑页面
    @ResponseBody
    @RequestMapping("/myAddressEdit")
    public ModelAndView myAddressEdit(HttpServletRequest request, String id, String updateAddressURL) {
        String htmlName = "shoppingApi/user/editaddress";
        request.getSession().setAttribute("updateAddressURL", updateAddressURL);
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();
        Address address = addressService.selectByUserIdTwo(Integer.parseInt(id));
        map.put("address", address);
        modelAndView.addObject("address", map);
        return modelAndView;
    }

    //检测用户是否登录
    @ResponseBody
    @RequestMapping("/verUserLogin")
    public Map<String, Object> verUserLogin(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        map.put("userNo", userNo);
        return map;
    }

    //用户中心设置默认地址
    @ResponseBody
    @RequestMapping("/updateDefaultAddress")
    public Map<String, Object> updateDefaultAddress(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String id = request.getParameter("Id");
        String updateAddressURL = (String) request.getSession().getAttribute("updateAddressURL");
        String isMoreAddress = (String) request.getSession().getAttribute("isMoreAddress");
        int isMoreAddressInt=0;try {
            isMoreAddressInt=Integer.parseInt(isMoreAddress);
        }catch (Exception e){}
        String orderNo = (String) request.getSession().getAttribute("orderNo");
        //修改该用户下默认地址
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        int ids = 0;
        int row = 0;
        int rows = 0;
        int userId = 0;
        if (userNo != null) {
            userId = userNo.getId();
        }
        Address addressT=new Address();
        if (id != null && !"".equals(id)) {
            ids = Integer.parseInt(id);
            //修改地址的默认值
            if(userId>0) {
                //活动特殊地址
                addressT=addressService.selectDefault(1,userId);
                //System.out.println("addressT:"+addressT);
                //
                rows = addressService.updateAddressStateByUserId(userId);
            }
            if (rows > 0) {
                Address addressTemp=addressService.selectByPrimaryKey(ids);
                //System.out.println("addressTemp:"+addressTemp);
                if(isMoreAddressInt==1){
                 int ss=addressService.updateDefaultAddress(addressT.getId());
                   // System.out.println("ss:"+ss);
                }
                addressTemp.setIsMoreAddress(isMoreAddressInt);
                if(isMoreAddressInt!=1) {
                    addressTemp.setIsdefault(1);
                }
                row = addressService.updateByPrimaryKey(addressTemp);
                //修改地址之后同步更新地址id到订单表
                if (orderNo != null&&!"".equals(orderNo)&&!"null".equals(orderNo)) {// 从订单详情页面来的才进行更新订单地址操作
                    Address address = addressService.selectByPrimaryKey(ids);
                    int reso=0;
                    OrderAddress orderAddress = new OrderAddress();
                orderAddress.setProvinceId(address.getProvinceId());
                orderAddress.setCityId(address.getCityId());
                orderAddress.setAreaId(address.getAreaId());
                orderAddress.setUserId(address.getUserId());
                orderAddress.setName(address.getName());
                orderAddress.setPhone(address.getPhone());
                orderAddress.setDetailAddr(address.getDetailAddr());
                orderAddress.setLogType(2);
                    OrderAddress orderAddress1=orderAddressService.selectByOrderAddress(orderAddress);
                    if(orderAddress1!=null){
                        orderService.updateOrderAddressId(orderAddress1.getId().toString(), orderNo);
                    }else {
                        reso = orderAddressService.insertSelective(orderAddress);
                    }
                    if (reso > 0) {
                        int res1 = orderService.updateOrderAddressId(orderAddress.getId().toString(), orderNo);
                    }
                }
            }
            if (row > 0) {
                map.put("updateState", "000001");//修改成功
                map.put("updateAddressURL", updateAddressURL);
            } else {
                map.put("updateState", "000000");//修改失败
            }
        }
        return map;
    }

    /**
     * 结算用户购买商品获得积分
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/calculateFinace")
    public Map<String, Object> calculateFinace(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String days = request.getParameter("days");
        int day = 0;
        Timestamp startTime = null;
        Timestamp endTime = null;
        if (days != null && days != "") {
            day = Integer.parseInt(days);
        }

        if (day == 1) {//每天
            startTime = new Timestamp(DateUtils.getDayBegin().getTime());
            endTime = new Timestamp(DateUtils.getDayEnd().getTime());
        } else if (day == 7) {//每周
            Date date = new Date();
            String date1 = DateUtils.getTimeInterval(date);
            String dateTime[] = date1.split(",");
            startTime = Timestamp.valueOf(dateTime[0]);
            endTime = Timestamp.valueOf(dateTime[1]);

        } else if (day == 30) {//每月
            Date startMonth = DateUtils.getBeginDayOfMonth();
            Date endMonth = DateUtils.getEndDayOfMonth();
            startTime = new Timestamp(startMonth.getTime());
            endTime = new Timestamp(endMonth.getTime());
        }

        //获取用户信息
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        int userNoId = 0;//用户编号Id
        List<UserNo> userNoList = null;
        List<Order> orderList = null;
        int coupon = 0;
        int couponTotal = 0;//总运营成本
        int rank = 0;
        double commission = 0.00;
        double couponTiChengMoney = 0.00;
        if (userNo != null) {

            userNoId = userNo.getId();
            rank = userNo.getRank();
            UserRank userRank = userRankService.selectByPrimaryKey(rank);
            commission = userRank.getCommission();
            userNoList = HuiYuanEarnings(userNoId);//查询多有该用户编号的直接推荐人

            OrderToData orderToData = new OrderToData();
            orderToData.setUserNoId(userNoId);
            orderToData.setStartTime(startTime);
            orderToData.setEndTime(endTime);

            if (userNoList != null && userNoList.size() != 0) {//还有间接的推荐人
                //递归调用查询所有的间接推荐人
                for (int i = 0; i < userNoList.size(); i++) {
                    userNoId = userNoList.get(i).getId();
                    if (userNoId != 0) {//用户编号Id不为0
                        userNoList = HuiYuanEarnings(userNoId);
                        //查询的推荐人已经支付的订单
                        orderList = selectPayOrder(orderToData);
                        //计算订单的运营成本
                        if (orderList.size() != 0 && orderList != null) {
                            for (int j = 0; j < orderList.size(); j++) {
                                coupon = orderList.get(j).getCoupon().intValue();
                                couponTotal += coupon;
                                System.out.println("运营成本：" + couponTotal);
                            }
                        }
                        //运营提成
                        couponTiChengMoney = couponTotal * commission / 100;
                    } else {
                        break;
                    }
                }
                System.out.println("运营提成：" + couponTiChengMoney);
            } else {//当用户还没有直接推荐人时候
                orderList = selectPayOrder(orderToData);
                //计算订单的运营成本
                if (orderList.size() != 0 && orderList != null) {
                    for (int k = 0; k < orderList.size(); k++) {
                        coupon = orderList.get(k).getCoupon().intValue();
                        couponTotal += coupon;
                        System.out.println("运营成本：" + couponTotal);
                    }
                }
                //运营提成
                couponTiChengMoney = couponTotal * commission / 100;
            }
        }
        map.put("couponTiChengMoney", couponTiChengMoney);
        return map;
    }

    //用户收益计算
    public List<UserNo> HuiYuanEarnings(int userNoId) {
        //用户编号
        UserNo userNo = sysUserNoService.selectByPrimaryKey(userNoId);
        //查询所有的用户的推荐人id都是该用户编号的Id
        List<UserNo> userNoList = sysUserNoService.selectAllNextUserNoByRecommend(userNoId);
        return userNoList;
    }

    public List<Order> selectPayOrder(OrderToData orderToData) {
        List<Order> orderList = null;
        orderList = orderService.selectPayOrderByUserNoId(orderToData);//根据用户编号id查询订单
        return orderList;
    }

    /*会员中心-设置账户--修改登录密码*/
    @RequestMapping("/updateLoginPwd")
    public ModelAndView updateLoginPwd(HttpServletRequest request) {
        ModelAndView modelAndView = null;
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        if (userNo != null) {
            modelAndView = new ModelAndView("shoppingApi/user/changeloginpassword");
            User user = userService.selectByPrimaryKey(userNo.getUserId());
            modelAndView.addObject("phone", user.getPhone());
            modelAndView.addObject("userNo", userNo.getUserNo());
        } else {
            modelAndView = new ModelAndView("shoppingApi/user/loginbyphone");
        }
        return modelAndView;
    }

    /*会员中心-设置账户--修改支付密码*/
    @RequestMapping("/updatePayPwd")
    public ModelAndView updatePayPwd(HttpServletRequest request) {
        ModelAndView modelAndView = null;
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        String redirect = request.getParameter("redirect");
        if (redirect != null) {
            request.getSession().setAttribute("redirect", redirect);
        }
        if (userNo != null) {
            modelAndView = new ModelAndView("shoppingApi/user/changepaypassword");
            User user = userService.selectByPrimaryKey(userNo.getUserId());
            modelAndView.addObject("phone", user.getPhone());
            modelAndView.addObject("userNo", userNo.getUserNo());
        } else {
            modelAndView = new ModelAndView("shoppingApi/user/loginbyphone");
        }
        return modelAndView;
    }

    /*修改支付密码*/
    @ResponseBody
    @RequestMapping(value = "/updatePayPwd", method = RequestMethod.POST)
    public Map<String, Object> updatePwd(javax.servlet.http.HttpServletRequest request) {
        UserNo userNoSession = (UserNo) request.getSession().getAttribute("userNo");
        Map<String, Object> map = new HashMap<>();
        String pwd = request.getParameter("pwd");
        String userNo = request.getParameter("userNo");
        String redirect = (String) request.getSession().getAttribute("redirect");
        if (pwd != null && pwd != "" && userNo != null && userNo != "") {
            try {
                UserNo userNo1 = sysUserNoService.selectUserNoByUserNo(userNo);
                System.out.println("userid=====" + userNo1.getId());
                UserNo userNo2 = new UserNo();
                String encryptedPwd = MD5Util.getEncryptedPwd(pwd);
//                userNo1.setPwd(encryptedPwd);
                userNo2.setPayPwd(encryptedPwd);
                userNo2.setId(userNo1.getId());
                int row = sysUserNoService.updateByPrimaryKeySelective(userNo2);
                if (row > 0) {
                    map.put("msg", "1");
                    if (userNoSession != null) {
                        userNoSession.setPayPwd(encryptedPwd);
                        request.getSession().setAttribute("userNo", userNoSession);
                    }

                } else {
                    map.put("mag", "0");
                }
                System.out.println(redirect + "ssssss");
                if (redirect != "" || redirect != null || redirect != "null") {
                    map.put("url", redirect);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /*验证支付密码*/
    @ResponseBody
    @RequestMapping(value = "/valPayPwd", method = RequestMethod.POST)
    public Map<String, Object> valPayPwd(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String payPwd = request.getParameter("payPwd");
        String pwdInDb = null;
        boolean flag = false;
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        if (userNo != null) {
            pwdInDb = userNo.getPayPwd();
        }
        try {
            flag = MD5Util.validPassword(payPwd, pwdInDb);//验证密码是否正确
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("flag", flag);
        return map;
    }

    /*提现页面*/
    @RequestMapping("/openWithDrawals")
    public ModelAndView openWithDrawals(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/withdraw");
        Map<String, Object> map = new HashMap<>();
        String userNo=request.getParameter("userNo");
        String pwd=null;
        if(userNo!=null&&userNo!=""){
            UserNo userNo1=sysUserNoService.selectUserNoByUserNo(userNo);
            if(userNo1!=null){
                pwd=userNo1.getPayPwd();
                if(pwd!=null&&pwd!=""){
                    map.put("msg","1");
                }
            }
        }
        modelAndView.addObject("map", map);
        return modelAndView;
    }


    /*积分提现信息*/
    @ResponseBody
    @RequestMapping("/openChangeFinace")
    public Map<String, Object> openChangeFinace(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        int userNoId = 0;
        FinaceTotal finaceTotal = null;
        if (userNo != null) {
            userNoId = userNo.getId();
            String user_No=userNo.getUserNo();//编号
            map.put("userNo", userNo);
            map.put("user_no",user_No);
        }
        //查询该用户的银行卡信息
       List<Withdrawals> withdrawalsList = withdrawalsService.selectWithdrawalsByUserNoId(userNoId);
        if (withdrawalsList != null&&withdrawalsList.size()!=0) {
            map.put("withdrawalsList", withdrawalsList);
    }
        //用户的积分余额
        finaceTotal = finaceTotalService.selectFinaceTotal(userNoId, "1");//查询积分
        if (finaceTotal != null) {
            map.put("finaceTotal", finaceTotal);
        }

        return map;
    }

    /*提现*/
    @ResponseBody
    @RequestMapping(value = "/withdrawals", method = RequestMethod.POST)
    public Map<String, Object> withdrawals(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String username = request.getParameter("username");
        String account = request.getParameter("account");
        String bankName = request.getParameter("bankName");
        String cashCount = request.getParameter("cashCount");
        int cashCounts = 0;
        int userNoId = 0;
        double balance = 0.00;
        double balance1 = 0.00;
        int fId = 0;
        if (cashCount != null && cashCount != "") {
            cashCounts = Integer.parseInt(cashCount);
        }
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        if (userNo != null) {
            userNoId = userNo.getId();
        }

        Withdrawals withdrawals = new Withdrawals();
        withdrawals.setAccount(account);
        withdrawals.setBankName(bankName);
        withdrawals.setCashCount(cashCounts);
        withdrawals.setUsername(username);
        withdrawals.setUserNoId(userNoId);
        withdrawals.setApplyTime(new Timestamp(System.currentTimeMillis()));
        withdrawals.setOpratorId(userNoId);


        //手续费
        double  changMoney=0.00;
        changMoney=cashCounts * fianceConfig.getPercent();
        if(changMoney<fianceConfig.getChangMoney()){
            changMoney=fianceConfig.getChangMoney();
        }
        withdrawals.setChangeMoney(changMoney);
        withdrawals.setTixianSign("1");
        //查询用户的积分余额
        FinaceTotal finaceTotal1 = finaceTotalService.selectFinaceTotal(userNoId, "1");
        if (finaceTotal1 != null) {
            balance = finaceTotal1.getBalance();
            fId = finaceTotal1.getfId();
        }

        FinaceTotal finaceTotal = new FinaceTotal();
        finaceTotal.setfType("1");
        finaceTotal.setUserId(userNoId);
        balance1 = balance - (cashCounts +changMoney);
        finaceTotal.setBalance(balance1);
        finaceTotal.setChanggeTime(new Timestamp(System.currentTimeMillis()));
        finaceTotal.setOpratorId(userNoId);
        finaceTotal.setfId(fId);

        //转让的用户积分添加该转让记录
        FinaceToData finaceToData = new FinaceToData();
        finaceToData.setUserId(userNoId);
        finaceToData.setClassify(1);
        finaceToData.setAmount(new BigDecimal(-(cashCounts + changMoney)));//金额
        finaceToData.setBalance(new BigDecimal(balance1));
        finaceToData.setFinaceTime(new Timestamp(System.currentTimeMillis()));
        finaceToData.setFinaceType("111");
        finaceToData.setRemark("提现"+account);
        finaceToData.setOpratorId(userNoId);


            int row1 = withdrawalsService.insert(withdrawals);
            int row2 = finaceTotalService.updateByPrimaryKeySelective(finaceTotal);//更新用户积分总余额
            int row3 = finaceService.insertFinaceData(finaceToData);
            if (row1 > 0 && row2 > 0 && row3 > 0) {
                map.put("msg", "1");
            } else {
                map.put("msg", "0");
            }

        return map;
    }

    /*转让页面*/
    @RequestMapping("/openTransfer")
    public ModelAndView openTransfer(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/user/transfer");
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");

        Map<String, Object> map = new HashMap<>();
        if (userNo != null) {
            map.put("userNo", userNo);
            if (!"".equals(userNo.getPayPwd())) {//支付密码不为空
                map.put("paystate", true);
            } else {
                map.put("paystate", false);
            }
        }
        int userNoId = userNo.getId();
        FinaceTotal finaceTotal1 = finaceTotalService.selectFinaceTotal(userNoId, "1");
        if (finaceTotal1 != null) {
            map.put("finaceTotal", finaceTotal1);
        } else {
            map.put("finaceTotal", null);
        }
        modelAndView.addObject("map", map);
        return modelAndView;
    }

    /*转让积分*/
    @ResponseBody
    @Transactional
    @RequestMapping(value = "/transferFinace", method = RequestMethod.POST)
    public Map<String, Object> transferFinace(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //用户登录
        int userNoId = 0;
        UserNo userNo2 = null;
        double cashCount = 0.00;
        double balance = 0.00;
        FinaceTotal finaceTotal1 = null;
        double changeBalance = 0.00;
        int changUserNoId = 0;
        double transferBalance = 0;
        int fId = 0;
        int row = 0;
        int changeFId = 0;
        int row1 = 0;
        int row2 = 0;
        int rows = 0;
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        if (userNo != null) {
            userNoId = userNo.getId();
        }else{
            map.put("msg", "1");
            return map;
        }
        //转让给用户的用户编号
        String userNo1 = request.getParameter("userNo");
        if (userNo1 != null && userNo1 != "") {
            userNo2 = sysUserNoService.selectUserNoByUserNo(userNo1);
            if (userNo2 != null) {
                changUserNoId = userNo2.getId();
            }else{
                map.put("msg", "1");
                return map;
            }
        }else{
            map.put("msg", "1");
            return map;
        }
        //转让金额
        String cashCounts = request.getParameter("cashCount");
        if (cashCounts != null && cashCounts != "") {
            cashCount = Double.parseDouble(cashCounts);
        }


        FinaceTotal finaceTotal = finaceTotalService.selectFinaceTotal(userNoId, "1");
        if (finaceTotal != null) {
            balance = finaceTotal.getBalance();
            fId = finaceTotal.getfId();
        }
        //


        //接受转让的用户的积分余额
        FinaceTotal changFinaceTotal = finaceTotalService.selectFinaceTotal(changUserNoId, "1");
        if (changFinaceTotal != null) {
            transferBalance = changFinaceTotal.getBalance();
            changeFId = changFinaceTotal.getfId();
        }
        //转让手续费
//        double charge=cashCount*fianceConfig.getPercent();

        if (balance >= cashCount) {//转让
            changeBalance = balance - cashCount;
            //更新用户积分的余额
            finaceTotal1 = new FinaceTotal();
            finaceTotal1.setfType("1");
            finaceTotal1.setBalance(changeBalance);
            finaceTotal1.setUserId(userNoId);
            finaceTotal1.setChanggeTime(new Timestamp(System.currentTimeMillis()));
            finaceTotal1.setfId(fId);
            finaceTotal1.setOpratorId(userNoId);
            row = finaceTotalService.updateByPrimaryKeySelective(finaceTotal1);

            if (row > 0) {
                //转让的用户积分添加该转让记录
                FinaceToData finaceToData = new FinaceToData();
                finaceToData.setUserId(userNoId);
                finaceToData.setClassify(1);
                finaceToData.setAmount(new BigDecimal(-cashCount));
                finaceToData.setBalance(new BigDecimal(changeBalance));
                finaceToData.setFinaceTime(new Timestamp(System.currentTimeMillis()));
                finaceToData.setFinaceType("111");
                finaceToData.setRemark("转出到"+userNo2.getUserNo());
                finaceToData.setOpratorId(userNoId);
                rows = finaceService.insertFinaceData(finaceToData);
            }else{
                throw new RuntimeException();
            }

            if (row > 0 && rows > 0) {//接受转让的用户积分更新
                //更新用户积分的余额
                FinaceTotal finaceTotal2 = new FinaceTotal();
                finaceTotal2.setfType("1");
                finaceTotal2.setBalance(transferBalance + cashCount);
                finaceTotal2.setUserId(changUserNoId);
                finaceTotal2.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                finaceTotal2.setOpratorId(changUserNoId);
                finaceTotal2.setOpratorUId(changUserNoId);

                if (changFinaceTotal != null) {
                    finaceTotal2.setfId(changeFId);
                    row1 = finaceTotalService.updateByPrimaryKeySelective(finaceTotal2);//更新用户积分总余额
                } else {
                    row1 = finaceTotalService.insertSelective(finaceTotal2);
                }

                if (row1 > 0) {
                    FinaceToData finaceToData = new FinaceToData();
                    finaceToData.setUserId(changUserNoId);
                    finaceToData.setClassify(1);
                    finaceToData.setAmount(new BigDecimal(+cashCount));//接受转让用户为正
                    finaceToData.setBalance(new BigDecimal(transferBalance + (cashCount)));
                    finaceToData.setFinaceTime(new Timestamp(System.currentTimeMillis()));
                    finaceToData.setFinaceType("111");
                    finaceToData.setRemark(userNo.getUserNo()+"转进");
                    finaceToData.setOpratorId(userNoId);
                    row2 = finaceService.insertFinaceData(finaceToData);
                }else{
                    throw new RuntimeException();
                }
                if (row1 > 0 && row2 > 0) {
                    map.put("msg", "1");
                }
            }else{
                throw new RuntimeException();
            }
        }else{
            map.put("msg", "1");
            return map;
        }

        return map;
    }

    /*结算用户的业绩---订单中商品的运营成本*/
    @ResponseBody
    @RequestMapping("/calculateOpratorcost")
    public Map<String, Object> calculateOpratorcost(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String days = request.getParameter("days");
        int day = 0;
        Timestamp startTime = null;
        Timestamp endTime = null;
        if (days != null && days != "") {
            day = Integer.parseInt(days);
        }

        if (day == 1) {//每天
            startTime = new Timestamp(DateUtils.getDayBegin().getTime());
            endTime = new Timestamp(DateUtils.getDayEnd().getTime());
        } else if (day == 7) {//每周
            Date date = new Date();
            String date1 = DateUtils.getTimeInterval(date);
            String dateTime[] = date1.split(",");
            startTime = Timestamp.valueOf(dateTime[0]);
            endTime = Timestamp.valueOf(dateTime[1]);

        } else if (day == 30) {//每月
            Date startMonth = DateUtils.getBeginDayOfMonth();
            Date endMonth = DateUtils.getEndDayOfMonth();
            startTime = new Timestamp(startMonth.getTime());
            endTime = new Timestamp(endMonth.getTime());
        }
        //获取用户信息
        UserNo userNo = (UserNo) request.getSession().getAttribute("userNo");
        if (userNo == null) {
            map.put("msg", "0");
            return map;
        }
        int userNoId = userNo.getId();//用户编号id
        OrderToData orderToData = new OrderToData();
        orderToData.setStartTime(startTime);
        orderToData.setEndTime(endTime);
        orderToData.setUserNoId(userNoId);
        orderToData.setOrderStatus("702");

        List<Order> orderList = orderService.selectOrderListByPayTime(orderToData);
        double orderOpratorcostSum = 0.00;//订单运营成本
        for (int i = 0; i < orderList.size(); i++) {
            if (orderList.get(i) != null && orderList.get(i).getOpratorCost() != null) {
                orderOpratorcostSum += orderList.get(i).getOpratorCost().doubleValue();
            } else {
                break;
            }

        }


        return map;

    }


//添加会员编号（绑定）-手机登录情况

    @ResponseBody
    @RequestMapping("/bindUserNo")
    public ModelAndView bindUserNo(HttpServletRequest request) {
        String htmlName = "shoppingApi/user/inputaccount";
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        if (!loginOut.checkLogin(request)) {
            userNo1 = null;
        }
        ModelAndView modelAndView = new ModelAndView(htmlName);
        Map<String, Object> map = new HashMap<>();
        return modelAndView;
    }

    /*
添加会员编号（绑定） 提交绑定
*/
    @ResponseBody
    @RequestMapping("/sendBindUserNo")
    public String sendBindUserNo(HttpServletRequest request, String userno, String pwd) {
        return "";
//        String json;
//        UserNo userNo=userNoService.selectUserByUserNO(userno);
//        String pedT=pwd;
//        HttpSession session = request.getSession();
//        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
//        if (!loginOut.checkLogin(request)) {
//            userNo1=null;
//        }
//        if(userNo!=null){
//            String userNoPwd=userNo.getPwd().toLowerCase();
//            if(!userNoPwd.equals(""))//社区店有密码
//            {
//                pwd=Md5.MD5(pwd).toLowerCase();
//                if(!userNo.getSalt().equals("")&&!userNo.getSalt().equals("0")){
//                    pwd=Md5.MD5(pwd+userNo.getSalt().toLowerCase());
//                }
//                if(!pwd.equals(userNoPwd)){
//                    json="{\"stat\":\"102\",\"message\":\"用户密码错误001!\"}";
//                    return json;
//                }
//                else {
//                    userNo.setUserId(userNo1.getUserId());//会员ID绑定赋值
//                }
//            }
//            else{
//                String jsonUrl = "http://yc.huisheng2688.com/hsycMgr/app/getUserInfo.do";
//                String param= "userid=" + userno+"&password=" + pwd+"&clientIp=127.0.0.1"+"&encryptStr="+ Md5.MD5("ts785a32").toLowerCase();
//                String jsonText = HttpRequest.sendGet(jsonUrl, param);
//                Order.hsysUser parseObject = JSON.parseObject(jsonText, Order.hsysUser.class);
//                Boolean hsbl=false;
//                if(parseObject.getSuccess().toLowerCase().equals("true")){
//                    hsbl=true;
//                }
//                if(!hsbl){
//                    json="{\"stat\":\"102\",\"message\":\"用户密码错误002!\"}";
//                }
//                else {
//                    userNo.setUserId(userNo1.getUserId());//会员ID绑定赋值
//                }
//            }
//            Integer res=userNoService.updateByPrimaryKeySelective(userNo);
//            if(res>0){
//                session.setAttribute("userNo", userNo);
//                json="{\"stat\":\"100\",\"message\":\"绑定成功!\"}";
//            }
//            else{
//                json="{\"stat\":\"104\",\"message\":\"绑定失败!\"}";
//            }
//        }
//        else {
//            json="{\"stat\":\"103\",\"message\":\"编号不存在!\"}";
//        }
//        return json;
    }


//    //切换账号-手机号登录
//    @ResponseBody
//    @RequestMapping("/user/ChangeUserPhone")
//    public String ChangeUserPhone(HttpServletRequest request,String userNo) {
//        HttpSession session = request.getSession();
//        UserNo userNoNew = userNoService.selectLogin(userNo);
//        String json;
//        if(userNoNew!=null)
//        {
//            session.setAttribute("userNo", userNoNew);
//            json = "{\"stat\":\"100\",\"message\":\"成功!\"}";
//        }
//        else {
//            json = "{\"stat\":\"200\",\"message\":\"失败!\"}";
//        }
//        return json;
//    }

}
